﻿@page "/samples/TimerRefresh"
@implements IDisposable
@using System.Threading

<h3>Timer定时刷新示例</h3>
<p>Current count: @currentCount</p>

<button class="btn btn-primary"
        @onclick="StartTimer"
        disabled="@isRunning">
    @buttonText
</button>

@code {
    private int currentCount = 0;
    private bool isRunning = false;
    private string buttonText => isRunning ? "运行中..." : "开始计时";
    private  System.Threading.Timer? timer;
    private readonly object syncLock = new();

    private void StartTimer()
    {
        if (!isRunning)
        {
            timer = new System.Threading.Timer(TimerCallback, null, 1000, 1000);
            isRunning = true;
        }
    }

    private void TimerCallback(object? state)
    {
        lock (syncLock)
        {
            currentCount++;
        }

        InvokeAsync(StateHasChanged);
    }

    public void Dispose()
    {
        timer?.Dispose();
    }
}
